#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务分配数据模型
"""

from database import db
from datetime import datetime
import uuid

class Task(db.Model):
    __tablename__ = 'tasks'
    
    id = db.Column(db.Integer, primary_key=True)
    task_no = db.Column(db.String(32), unique=True, nullable=False, comment='任务编号')
    title = db.Column(db.String(200), nullable=False, comment='任务标题')
    description = db.Column(db.Text, nullable=True, comment='任务描述')
    
    # 任务分配
    assigned_by = db.Column(db.Integer, db.ForeignKey('admins.id'), nullable=False, comment='分配人（管理员）')
    staff_id = db.Column(db.Integer, db.ForeignKey('staff.id'), nullable=False, comment='执行人（员工）')
    table_id = db.Column(db.Integer, db.ForeignKey('billiard_tables.id'), nullable=True, comment='相关台球桌')
    
    # 任务信息
    task_type = db.Column(db.String(50), nullable=False, comment='任务类型：cleaning清洁，maintenance维护，service服务，other其他')
    priority = db.Column(db.String(20), default='normal', comment='优先级：low低，normal普通，high高，urgent紧急')
    
    # 时间安排
    start_time = db.Column(db.DateTime, nullable=True, comment='开始时间')
    end_time = db.Column(db.DateTime, nullable=True, comment='结束时间')
    deadline = db.Column(db.DateTime, nullable=True, comment='截止时间')
    
    # 任务状态
    status = db.Column(db.String(20), default='pending', comment='状态：pending待执行，in_progress执行中，completed已完成，cancelled已取消')
    
    # 执行结果
    result = db.Column(db.Text, nullable=True, comment='执行结果')
    completion_note = db.Column(db.Text, nullable=True, comment='完成备注')
    completion_time = db.Column(db.DateTime, nullable=True, comment='完成时间')
    
    # 系统字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    assigner = db.relationship('Admin', foreign_keys=[assigned_by])
    table = db.relationship('BilliardTable', foreign_keys=[table_id])
    
    def __init__(self, **kwargs):
        super(Task, self).__init__(**kwargs)
        if not self.task_no:
            self.task_no = self.generate_task_no()
    
    @staticmethod
    def generate_task_no():
        """生成任务编号"""
        prefix = datetime.now().strftime('%Y%m%d')
        suffix = str(uuid.uuid4()).replace('-', '')[:8].upper()
        return f'TK{prefix}{suffix}'
    
    def to_dict(self):
        return {
            'id': self.id,
            'task_no': self.task_no,
            'title': self.title,
            'description': self.description,
            'assigned_by': self.assigned_by,
            'staff_id': self.staff_id,
            'table_id': self.table_id,
            'task_type': self.task_type,
            'priority': self.priority,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'deadline': self.deadline.isoformat() if self.deadline else None,
            'status': self.status,
            'result': self.result,
            'completion_note': self.completion_note,
            'completion_time': self.completion_time.isoformat() if self.completion_time else None,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'assigner': self.assigner.to_dict() if self.assigner else None,
            'staff': self.staff.to_dict() if self.staff else None,
            'table': self.table.to_dict() if self.table else None
        }
    
    def __repr__(self):
        return f'<Task {self.task_no}>'